package com.ldk.base.framework.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * MD5\SHA-1加密工具类
 * @author xiangwl
 *
 */
public class EncryptUtil {
	
	/**
	 * 32位md5加密
	 * @param inputText
	 * @return
	 */
	public static String md5(String inputText)
	{
		return md5(inputText, 32);
	}
	
	/**
	 * md5 加密
	 * @param inputText 加密字符
	 * @param bit 位数32或16位
	 * @return
	 */
	public static String md5(String inputText, int bit){
		String encryptString = encrypt(inputText, "md5");
		if(bit == 16){
			encryptString = encryptString.substring(8, 24);
		}
		return encryptString;
	}
	
	/**
	 * SHA-1加密
	 * @param inputText
	 * @return
	 */
	public static String sha(String inputText)
	{
		return encrypt(inputText, "sha-1");
	}
	
	/**
	 * des加密
	 * @param data
	 * @param key
	 * @return
	 */
	public static String desEncrypt(String data, String key){
		try{
			byte[] bytes = data.getBytes("UTF-8");
			byte[] keys = key.getBytes("UTF-8");
			
			// 生成一个可信任的随机数源
			SecureRandom sr = new SecureRandom();

			// 从原始密钥数据创建DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(keys);

			// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(dks);

			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance("DES");

			// 用密钥初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
			
			return byte2hex(cipher.doFinal(bytes));
		}
		catch(Exception e){
			
		}
		return "";
	}
	
	
	/**
	 * des 解密
	 * @param data
	 * @param key
	 * @return
	 */
	public static String desDecrypt(String data, String key){
		try{
			byte[] bytes = hex2byte(data);
			byte[] keys = key.getBytes("UTF-8");
			
			// 生成一个可信任的随机数源
			SecureRandom sr = new SecureRandom();

			// 从原始密钥数据创建DESKeySpec对象
			DESKeySpec dks = new DESKeySpec(keys);

			// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(dks);

			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance("DES");

			// 用密钥初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
			
			return new String(cipher.doFinal(bytes), "UTF-8");
		}
		catch(Exception e){
			
		}
		return "";
	}
	
	
	/**
	 * 加密
	 * @param inputText 加密字符串
	 * @param algorithmName 加密算法
	 * @return
	 */
	private static String encrypt(String inputText, String algorithmName){
		if(inputText == null || "".equals(inputText.trim()))
		{
			throw new IllegalArgumentException("请输入加密字符串");
		}
		if(algorithmName == null || "".equals(algorithmName.trim()))
		{
			algorithmName = "md5";
		}
		String encryptText = null;  
        try {  
            MessageDigest m = MessageDigest.getInstance(algorithmName);  
            m.update(inputText.getBytes("UTF8"));  
            byte s[] = m.digest();    
            return byte2hex(s);  
            
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return encryptText;  
	}
	
	/**
	 * 返回十六进制的字符串
	 * @param bytes
	 * @return
	 */
	private static String byte2hex(byte[] bytes)
	{
		if(bytes == null || bytes.length < 1) return "";
		StringBuilder sb = new StringBuilder();
		
		for(byte it:bytes){
			String str = Integer.toHexString((it & 0xFF) | 0x100).substring(1,3);
			sb.append(str);
		}
		return sb.toString();
	}
	
	private static byte[] hex2byte(String hex){
		try{
			byte[] b = hex.getBytes("UTF-8");
			if ((b.length % 2) != 0)  
				throw new IllegalArgumentException("长度不是偶数");  
			byte[] b2 = new byte[b.length / 2];  
			for (int n = 0; n < b.length; n += 2) {  
				String item = new String(b, n, 2);  
				b2[n / 2] = (byte) Integer.parseInt(item, 16);  
			}  
			return b2;
		}
		catch(Exception e){
			
		}
		return null;
	}
}
